package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.dto.ArticleStreamMessage;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.IHotArticleService;
import org.apache.commons.configuration.beanutils.BeanHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: itheima
 * @create: 2022-01-02 11:22
 */
@Service
public class HotArticleServiceImpl implements IHotArticleService {

    @Autowired
    private IApArticleService articleService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 将最近5天发布文章得分进行计算，将数据缓存到redis中ZSet数据结构中
     */
    @Override
    public void compute() {
        //1.查询最近5天（上架且发布状态）的文章列表
        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        //1.1 设置上架状态
        queryWrapper.eq(ApArticle::getIsDown, false);
        //1.2 设置删除状态
        queryWrapper.eq(ApArticle::getIsDelete, false);
        //1.3 设置日期区间 开始时间 结束时间
        // 获取当前的0点时间
        Date to = getFromAndToDate(0);
        // 获取前5天的时刻
        Date from = getFromAndToDate(-30);
        queryWrapper.between(ApArticle::getPublishTime, from, to);
        List<ApArticle> list = articleService.list(queryWrapper);
        //2.遍历文章列表，计算分值
        if (!CollectionUtils.isEmpty(list)) {
            //2.1 定义Redis热点数据key 前缀+0 首页   前缀+channelId  频道的key
            String redisKeyPrefix = "leadnews:article:hot:page:";
            for (ApArticle article : list) {
                //2.2 计算每篇文章得分
                int score = computeScore(article);
                //2.3 将文章缓存到redis中 ZSet结构中
                ApArticle cache = new ApArticle();
                cache.setId(article.getId());
                cache.setTitle(article.getTitle());
                cache.setImages(article.getImages());
                cache.setAuthorId(article.getAuthorId());
                cache.setAuthorName(article.getAuthorName());
                cache.setLayout(article.getLayout());
                cache.setStaticUrl(article.getStaticUrl());
                String value = JSON.toJSONString(cache);
                //2.4 将数据缓存到redis中 往首页中key中缓存数据 往每个频道中缓存数据
                String indexKey = redisKeyPrefix + "0";
                redisTemplate.opsForZSet().add(indexKey, value, score);

                String channalKey = redisKeyPrefix + article.getChannelId();
                redisTemplate.opsForZSet().add(channalKey, value, score);

                //设置过期时间1天
                redisTemplate.expire(indexKey, 1, TimeUnit.DAYS);
                redisTemplate.expire(channalKey, 1, TimeUnit.DAYS);
            }
        }
    }


    /**
     * 为入参的文章计算分值
     *
     * @param article
     * @return
     */
    private int computeScore(ApArticle article) {
        int score = 0;
        // 阅读 +1  点赞 +3  评论 +5  收藏 +8
        if (article.getViews() != null) {
            score += article.getViews() * 1;
        }
        if (article.getLikes() != null) {
            score += article.getLikes() * 3;
        }
        if (article.getComment() != null) {
            score += article.getComment() * 5;
        }
        if (article.getCollection() != null) {
            score += article.getCollection() * 8;
        }
        return score;
    }


    /**
     * 获取指定天数日期 正数：未来时间  负数：以前时间
     *
     * @param datecount
     * @return
     */
    public static Date getFromAndToDate(Integer datecount) {
        //创建日期对象
        Calendar calendar = Calendar.getInstance();
        //设置日期
        calendar.add(Calendar.DATE, datecount);
        //设置时分秒
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }


    /**
     * 根据实时热点文章流式计算结果，更新redis中文章数据，以及数据库中文章表中各种操作数值
     *
     * @param message
     */
    @Override
    @Transactional
    public void update(ArticleStreamMessage message) {
        //1.根据文章ID查询文章对象
        ApArticle article = articleService.getById(message.getArticleId());
        //2.构建Redis中缓存文章对象 一定要跟以前缓存数据属性一致
        ApArticle cache = new ApArticle();
        cache.setId(article.getId());
        cache.setTitle(article.getTitle());
        cache.setImages(article.getImages());
        cache.setAuthorId(article.getAuthorId());
        cache.setAuthorName(article.getAuthorName());
        cache.setLayout(article.getLayout());
        cache.setStaticUrl(article.getStaticUrl());
        String value = JSON.toJSONString(cache);

        //3.更新redis缓存文章数据
        String key = "leadnews:article:hot:page:0";  //首页缓存数据key
        //3.1 计算改文章增量得分(根据行为操作计算得分)
        int scorePlus = computeScore(message);

        //3.2 判断redis中是否包含该文章
        Double score = redisTemplate.opsForZSet().score(key, value);
        if (score != null) {
            //3.2.1 如果存在，直接在原来文章得分上+增量得分
            redisTemplate.opsForZSet().incrementScore(key, value, scorePlus);
        } else {
            //3.2.2 如果不存在 先计算原有文章历史得分+增量得分
            int historyScore = computeScore(article);
            redisTemplate.opsForZSet().add(key, value, historyScore + scorePlus);
        }

        //4.更新数据库中文章表行为操作数值
        LambdaUpdateWrapper<ApArticle> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ApArticle::getId, article.getId());
        updateWrapper.setSql("views = views +" + message.getView());
        updateWrapper.setSql("likes = likes +" + message.getLike());
        updateWrapper.setSql("comment = comment +" + message.getComment());
        updateWrapper.setSql("collection = collection +" + message.getCollect());
        articleService.update(updateWrapper);
    }

    /**
     * 计算当日的增量分数  当日的操作整体权重*3
     *
     * @param message
     * @return
     */
    private int computeScore(ArticleStreamMessage message) {
        int score = 0;
        score += message.getView() * 1 * 3;
        score += message.getLike() * 3 * 3;
        score += message.getComment() * 5 * 3;
        score += message.getCollect() * 8 * 3;
        return score;
    }
}
